package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.heima.common.constants.message.WmNewsUpDownConstants;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JsonUtils;
import com.heima.model.media.dtos.WmNewsDto;
import com.heima.model.media.dtos.WmNewsPageReqDto;
import com.heima.model.media.dtos.WmNewsResultDTO;
import com.heima.wemedia.entity.WmNews;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsAuditService;
import com.heima.wemedia.service.WmNewsMaterialService;
import com.heima.wemedia.service.WmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.lang.invoke.LambdaConversionException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import static com.heima.common.constants.message.WmNewsUpDownConstants.WM_NEWS_UP_OR_DOWN_TOPIC;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-02-15
 */
@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Override
    public PageResult<WmNewsResultDTO> findByPage(WmNewsPageReqDto dto) {
        Integer userId = UserThreadLocalUtils.getUserId();
//        分页设置
        IPage<WmNews> iPage = new Page<>(dto.getPage(),dto.getSize());
//        查询设置
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.
                eq(WmNews::getWmUserId,userId).
                like(StringUtils.isNotBlank(dto.getKeyword()),WmNews::getTitle,dto.getKeyword()).
                eq(dto.getChannelId() != null,WmNews::getChannelId,dto.getChannelId()).
                gt(dto.getBeginPubDate()!= null ,WmNews::getPublishTime,dto.getBeginPubDate()).
                lt(dto.getEndPubDate()!=null,WmNews::getPublishTime,dto.getEndPubDate());
        if(dto.getStatus() != null &&dto.getStatus()!= -1){
            if(dto.getStatus()==1){
//                状态1 ，包括 1,3   where status in (1,3)
                queryWrapper.in(WmNews::getStatus,1,3);
            }else if(dto.getStatus()==4){
//                状态 4 ，包括 4,8,9 where status in (4,8,9)
                queryWrapper.in(WmNews::getStatus,4,8,9);
            }else{
//                状态 0,2
                queryWrapper.eq(WmNews::getStatus,dto.getStatus());
            }
        }
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
//        分页查询
        IPage<WmNews> wmNewsIPage = page(iPage, queryWrapper);
        if(CollectionUtils.isEmpty(wmNewsIPage.getRecords())){
            log.error("没有查询到数据");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        构造结果
        return new PageResult<>(dto.getPage(),dto.getSize(),wmNewsIPage.getTotal(),
                BeanHelper.copyWithCollection(wmNewsIPage.getRecords(),WmNewsResultDTO.class));
    }


    @Autowired
    private WmNewsMaterialService newsMaterialService;
    @Autowired
    private WmMaterialService materialService;
    @Autowired
    private WmNewsAuditService wmNewsAuditService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submit(WmNewsDto dto) {
        Integer userId = UserThreadLocalUtils.getUserId();
//        对象属性拷贝
        WmNews wmNews = BeanHelper.copyProperties(dto,WmNews.class);
//        设置用户id
        wmNews.setWmUserId(userId);
        if(dto.getId()==null){
//            新增
            wmNews.setCreatedTime(new Date());
        }
        if(!dto.getDraft()){
//            提交
            wmNews.setSubmitedTime(new Date());
        }
        if(!CollectionUtils.isEmpty(dto.getImages())){
//            String images = "";
//            for (String image : dto.getImages()) {
//                if(images.length()>0){
//                    images +=",";
//                }
//                images += images;
//            }
            String images = dto.getImages().stream().collect(Collectors.joining(","));
            wmNews.setImages(images);
        }
//        新增，修改，提交审核  文章表
        boolean b = saveOrUpdate(wmNews);
        if(!b){
            log.error("操作文章表失败！");
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
//        获取文章id
        Integer wmNewsId = wmNews.getId();
//        如果修改，先根据文章id删除素材中间表数据
        if(dto.getId()!=null) {
//            修改操作，需要删除中间表
            newsMaterialService.removeByNewsId(wmNewsId);
        }
//        获取文章中的内容的素材id
        String content = wmNews.getContent();
//        把json字符串转对象
        List<Integer> contentMaterialIds = new ArrayList<>();
        List<Map<String,Object>>  list = JsonUtils.nativeRead(content, new TypeReference<List<Map<String, Object>>>() {});
        for (Map<String, Object> map : list) {
            String type = map.get("type").toString();
            if("image".equals(type)){
//                获取素材id
                Integer materialId = Integer.valueOf(map.get("id").toString());
                contentMaterialIds.add(materialId);
            }

        }
        if(!CollectionUtils.isEmpty(contentMaterialIds)) {
//              新增素材中间表数据
            newsMaterialService.saveNewsAndMaterialBatch(contentMaterialIds,wmNewsId,0);
        }
//        获取文章中的封面素材id
        if(!CollectionUtils.isEmpty(dto.getImages())){
//            [1.jpg,2.jpb,3.jpg]
//            select * from wm_material where url in (?)
//            根据url的集合查询 素材id的集合
            List<Integer> imagesMaterialIds = materialService.findByUrls(dto.getImages());
            if(!CollectionUtils.isEmpty(imagesMaterialIds)) {
//              新增素材中间表数据
                newsMaterialService.saveNewsAndMaterialBatch(imagesMaterialIds,wmNewsId,1);
            }
        }

        log.info("==文章保存完成！");
        //        调用审核的代码
        wmNewsAuditService.auditWmNews(wmNews);

    }

    @Override
    public WmNewsResultDTO findOneNews(Integer wmNewsId) {

        Integer userId = UserThreadLocalUtils.getUserId();

        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getWmUserId,userId).eq(WmNews::getId,wmNewsId);
        WmNews wmNews = getOne(queryWrapper);
        if(wmNews == null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return BeanHelper.copyProperties(wmNews,WmNewsResultDTO.class);
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /***
     * 上下架操作
     * @param wmNews
     * @return
     */
    @Override
    public void downOrUp(WmNews wmNews) {
//        获取登录用户信息
        Integer userId = UserThreadLocalUtils.getUserId();

        Integer wmNewsId = wmNews.getId();
//        根据文章id查询 自媒体文章
        WmNews wmNews1 = getById(wmNewsId);
//        判断是否存在
        if(wmNews1 == null){
            log.error("文章不存在！");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if(wmNews1.getWmUserId().intValue() != userId.intValue()){
            log.error("没有权限操作文章");
            throw new LeadException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
//        判断是否已经发布
        if(wmNews1.getStatus() !=9){
            log.error("不是发布状态！");
            throw new LeadException(AppHttpCodeEnum.NEWS_NOT_PUBLISH);
        }
//        修改自媒体文章上下架状态
        boolean b = updateById(wmNews);
        if(!b){
            log.error("更新失败");
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
//        发送kafka消息,articleId,enable
        Map<String,Long> map = new HashMap<>();
        map.put("articleId",wmNews1.getArticleId());
        map.put("enable",wmNews.getEnable()?1L:0L);
        String msg = JsonUtils.toString(map);
        log.info("消息内容={}",msg);
        kafkaTemplate.send(WM_NEWS_UP_OR_DOWN_TOPIC,msg);
    }
}
